-- UIActivityGoodsInfo
-- Create by chendh
-- 探索特殊商店商品信息界面

local TREASURE = 6;  -- 秘宝
local ROBOT = 8;     -- 机器人

-- UIActivityGoodsInfo继承自Layer
UIActivityGoodsInfo = class("UIActivityGoodsInfo", function()
    return cc.Layer:create();
end);

function UIActivityGoodsInfo.create(activityId, goodsId, extra)
    return UIActivityGoodsInfo.new(activityId, goodsId, extra);
end

-- 构造函数
function UIActivityGoodsInfo:ctor(activityId, goodsId, extra)
    self:setName("UIActivityGoodsInfo");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/shop/BlackMarketGoodsDetail.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 记录商品信息
    self.activityId = activityId;
    self.goodsId = goodsId;
    self.extra   = extra;

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 是否是天空活动
function UIActivityGoodsInfo:isSkyActivity()
    return ActivityM.query(self.activityId, "type") == ACTIVITY_TYPE_SKY;
end

-- 注册事件处理回调函数
function UIActivityGoodsInfo:registerEventCallback()
    -- 注册获得焦点的回调
    EventMgr.register("UIActivityGoodsInfo", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIActivityGoodsInfo" then
            -- 如果是天空活动
            if self:isSkyActivity() then
                -- TopMenu显示天空活动的数据和袭击次数
                local uiTopMenu = UIMgr:getCurrentScene().topMenu;
                uiTopMenu:setSkyActivityId(self.activityId);
                uiTopMenu:show(TOPMENU_FRAME_ACTIVITY_DATA, TOPMENU_FRAME_ACTIVITY_TIMES, TOPMENU_FRAME_HEAD_AIRSHIP);
            end
        end
    end);

    -- 关注活动关闭事件
    EventMgr.register("UIActivityGoodsInfo", event.ACTIVITY_CLOSE, function(args)
        -- 如果是当前活动关闭了，那么退出界面
        if self.activityId == args["id"] then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UIActivityGoodsInfo");
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UIActivityGoodsInfo");
        end
    end);
end

-- 注册点击事件
function UIActivityGoodsInfo:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UIActivityGoodsInfo");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确认购买按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/btn_buy");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 尝试购买
            self:tryBuy();
        end
    end
    btnBuy:addTouchEventListener(onBuyClick);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuy:setTitleText(getLocStr("btn_text_confirm_exchange"));
end

-- 重绘
function UIActivityGoodsInfo:redraw()
    -- 显示商品名称
    local CT = findChildByName(self.node, "CT");
    local nameLabel = CT:getChildByName("name");

    local goodsInfo;

    if self:isSkyActivity() then
        -- 天空活动
        goodsInfo = SkyActivityM.queryExchange(self.goodsId);
    else
        -- 其他活动
        goodsInfo = ActivityM.queryExchange(self.goodsId);
    end

    local goods = goodsInfo["bonus"];
    local goodsNum;
    local classId;
    local goodsType;
    local nameStr;
    local nameDesc;
    local desc;
    local extraDesc;

    if type(goods) == "table" then
        goodsNum = goods[3];
        classId = goods[2];
        goodsType = goods[1];
        if goodsType == 1 then
            nameStr = ItemM.query(classId, "name");
            desc = ItemM.getItemDesc(classId);
        elseif goodsType == 2 then
            nameStr = FieldsM.query(classId, "name");
            desc = FieldsM.query(classId, "desc");
        elseif goodsType == ROBOT then
            nameStr = SkyRobotM.query(classId, "name");
            desc = SkyRobotM.query(classId, "desc");
        else
            nameStr = SkyShipSkillM.query(classId, "name");
            desc = SkyShipSkillM.getShipSkillDesc(classId);
        end
    elseif type(self.extra) == "table" then
        goodsNum = 1;
        goodsType = self.extra["goods_type"];
        nameStr = self.extra["name"];
        desc = self.extra["desc"];
        extraDesc = self.extra["extra_desc"];
    end

    if goodsNum > 1 then
        nameDesc = string.format(getLocStr("item_bonus_format"), nameStr, goodsNum);
    else
        nameDesc = string.format(getLocStr("have_took_boss_gift"), nameStr);
    end

    -- 如果是限购的商品，需要显示限购次数
    local remainTimes;
    if not self:isSkyActivity() then
        remainTimes = ActivityM.getRemainExchangeAmount(self.activityId, self.goodsId);
    end

    local timesLimitTip = "";
    if type(remainTimes) == "number" and remainTimes > 0 then
        timesLimitTip = string.format(getLocStr("buy_times_limit"), remainTimes);
    end

    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
    local finalNameDesc = nameDesc .. timesLimitTip;
    if not isFullWidthLang() then
        -- 非全角字符基本都超长了，需要强制换行
        finalNameDesc = nameDesc .. "\n" .. timesLimitTip;
    end
    nameLabel = applyString(nameLabel, finalNameDesc);

    -- 显示商品描述
    local descLabel = CT:getChildByName("desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    descLabel = applyString(descLabel, desc);

    -- 显示细节描述
    local detail = "";

    if goodsType == 1 then
        -- 道具
        local itemDetail = ItemM.query(classId, "detail");
        if type(itemDetail) == "string" and string.len(itemDetail) > 0 then
            detail = "[blue]" .. itemDetail  .. "[-]\n";
        end
    elseif goodsType == 2 then
        -- 属性
        local attribDetail = FieldsM.query(classId, "detail");
        if type(attribDetail) == "string" and string.len(attribDetail) > 0 then
            detail = "[blue]" .. attribDetail  .. "[-]\n";
        end
    elseif goodsType == ROBOT then
        -- 机器人
        detail = "[blue]" .. SkyRobotM.query(classId, "prop_desc") .. "[-]\n";
    elseif goodsType == TREASURE then
        -- 秘宝增加额外描述
        detail = "[blue]" .. SkyShipSkillM.getShipSkillDetail(classId) .. "[-]\n\n";

        detail = detail .. "[red]" .. getLocStr("airship_skill_desc") .. "[-]\n";

        local group = SkyShipSkillM.query(classId, "group");
        for _, petId in ipairs(group) do
            if not ME.user.pets[petId] then
                detail = detail .. "[gray]" .. PetM.query(petId, "name") .. "[-]\n";
            else
                detail = detail .. "[blue]" .. PetM.query(petId, "name") .. "[-]\n";
            end
        end
    end

    -- 如果是符石，则描述里面要加一些内容
    local stoneStyle = SkyStoneM.query(classId, "style");
    if stoneStyle then
        local extra = string.format(getLocStr("stone_detail"), getLocStr("stone_style_" .. stoneStyle));
        detail = detail .. "\n" .. extra;
    end

    local detailLabel = CT:getChildByName("detail");
    if detail == "" then
        detailLabel:setVisible(false);
    else
        detailLabel:setVisible(true);
        TextStyleM.setTextStyle(detailLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
        detailLabel = applyString(detailLabel, detail);
    end

    -- 显示商品价格
    local price = goodsInfo["price"];

    -- 计算下消耗的勋章数量
    local priceAmount;
    local ownAmount;
    local fieldName;
    local attribDesc;

    if self:isSkyActivity() then
        -- 天空活动
        priceAmount = SkyActivityM.calcExchangeCostNum(self.activityId, self.goodsId);
        local activityData = SkyActivityM.getActivityData(self.activityId);
        local medalClassId = SkyActivityM.query(self.activityId, "medal_class_id");
        ownAmount = ItemM.getAmount(ME.user, medalClassId);
        fieldName = ItemM.query(medalClassId, "name");
    else
        -- 其他活动
        local price = goodsInfo["price"];
        priceAmount = price[3];
        if price[1] == 1 then
            ownAmount   = ItemM.getAmount(ME.user, price[2]);
            fieldName   = ItemM.query(price[2], "name");
        elseif price[1] == 2 then
            ownAmount = ME.user:queryAttrib(price[2]);
            fieldName = FieldsM.query(price[2], "name");
        end
    end

    attribDesc   = string.format(getLocStr("attrib_value_format"), ownAmount, priceAmount);
    if priceAmount > ownAmount then
        attribDesc = "[red]" .. attribDesc .. "[-]";
    end

    local costDesc = string.format(getLocStr("change_cost_scraps2"), fieldName, attribDesc);

    costDesc = costDesc .. "\n";

    if extraDesc then
        costDesc = costDesc .. extraDesc .. "\n";
    end

    -- 显示拥有商品数量
    local amountLabel = CT:getChildByName("own_amount");
    TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GREEN);

    if goodsType == 1 then
        local amount = ItemM.getOwnedAmount(ME.user, classId);
        costDesc = costDesc .. string.format(getLocStr("own_goods_amount2"), amount);
    elseif goodsType == 2 then
        local amount = ME.user:queryAttrib(classId);
        costDesc = costDesc .. string.format(getLocStr("own_goods_amount4"), amount);
    end
    amountLabel = applyString(amountLabel, costDesc);

    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg");
    local btnBuy = findChildByName(self.node, "CT/btn_buy");
    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL,
        { nameLabel, descLabel, detailLabel, amountLabel, btnBuy});

    -- 如果购买次数已用完，按钮置灰
    if remainTimes == 0 then
        setButtonEnabled(btnBuy, false);
    else
        setButtonEnabled(btnBuy, true);
    end

    -- 显示商品阶位
    local rank = 0;

    if goodsType == ROBOT then
        rank = SkyRobotM.query(classId, "rank") or 0;
    elseif goodsType ~= TREASURE then
        rank = ItemM.query(classId, "rank") or 0;
    end

    if rank > 0 then
        local needShow = false;
        if goodsType == ROBOT then
            needShow = true;
        else
            needShow = FormulaM.invoke("NEED_SHOW_STAR", classId);
        end
        if needShow then
            local starNode = findChildByName(self.node, "CT/star_node");
            local layer = createStarLayer(rank, "images/ui/symbol/star_large.png", "right");
            if layer then
                starNode:removeAllChildren();
                starNode:addChild(layer);
            end
            starNode:setPositionY(nameLabel:getPositionY());
        end
    end
end

-- 适配
function UIActivityGoodsInfo:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 尝试购买
function UIActivityGoodsInfo:tryBuy()
    -- 判断能否购买
    local ret;
    if self:isSkyActivity() then
        ret = SkyActivityM.canExchange(self.activityId, self.goodsId, 1);
    else
        ret = ActivityM.canExchange(self.activityId, self.goodsId, 1);
    end

    if ret ~= true then
        AudioM.playFx("market_buy_failed");
        if ret == "sold_out" then
            -- 商品已售完
            alert(getLocStr("goods_exchange_over"));
        elseif type(ret) == "string" and string.endWith(ret, "_lack") then
            -- 属性不足
            local field = string.sub(ret, 1, -6);
            if field == "gem" then
                showGemLackConfirm();
            else
                local fieldName;
                if string.startWith(field, "item_") then
                    local classId = tonumber(string.sub(field, 6, -1));
                    fieldName = ItemM.query(classId, "name");
                else
                    fieldName = FieldsM.getFieldName(field);
                end

                local msg = string.format(getLocStr("fail_to_do_operate2"), fieldName, getLocStr("exchange"));
                alert(msg);
            end
        end
        -- 关闭当前界面
        UIMgr.getCurrentScene():removeFormByName("UIActivityGoodsInfo");
        return;
    end

    -- 执行购买
    AudioM.playFx("market_buy_success");
    Operation.cmd_activity_exchange(self.activityId, self.goodsId, 1);

    -- 关闭当前界面
    UIMgr.getCurrentScene():removeFormByName("UIActivityGoodsInfo");
end

